#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-23 下午4:09
# @Author  : Tom
# @Site    : 
# @File    : skus.py
# @Software: PyCharm
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from meiduo_admin.serilizers import SkuSerializer, CategorySerializer, SpuSerilizer, SpecSerilizer
from meiduo_admin.utils import PageNumber_User


# sku的增删查改
class SkuView(ModelViewSet):
    # 添加序列化器和查询集
    serializer_class = SkuSerializer
    queryset = SKU.objects.all().order_by("id")
    # 指定分页类
    pagination_class = PageNumber_User
    permission_classes = [IsAdminUser, ]

    # 制定查询集
    def get_queryset(self):
        # 获取关键词 , queryset必须为查询列表，不能单为对象
        keyword = self.request.query_params.get("keyword")
        if keyword == "" or keyword is None:
            queryset = SKU.objects.order_by("id")
        else:
            queryset = SKU.objects.filter(name=keyword)
            if len(queryset) == 0:
                queryset = SKU.objects.filter(price=keyword)
            if len(queryset) == 0:
                queryset = SKU.objects.filter(stock=keyword)
            if len(queryset) == 0:
                queryset = SKU.objects.filter(sales=keyword)
            if len(queryset) == 0:
                queryset = SKU.objects.filter(category=keyword)
        return queryset

    # 获取商品的三级分类
    def Category(self, request):
        category = GoodsCategory.objects.filter(subs=None)
        ser = CategorySerializer(category, many=True)
        return Response(ser.data)

    # 获取商品的spu商品
    def GoodsSimple(self, request):
        spu = SPU.objects.order_by("id")
        ser = SpuSerilizer(spu, many=True)
        return Response(ser.data)

    # 获取商品的规格选项信息
    def goodsspecoption(self, reuqest, pk):
        spec = SPUSpecification.objects.filter(spu_id=pk)
        # 获取序列化器
        ser = SpecSerilizer(spec, many=True)
        return Response(ser.data)
